package chapter22;

import java.lang.reflect.Field;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author lzy
 * @version v1.0
 * Create DateTime: 2019/2/26 16:39
 */
public class SimpleFormatter implements ISimpleFormatter {
    public static void main(String[] args) throws ParseException, IllegalAccessException {
        ISimpleFormatter formatter = new SimpleFormatter();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Student student = new Student("小马", format.parse("1990-07-09"), 98.1);
        System.out.println(formatter.format(student));
    }

    @Override
    public String format(Object object) throws IllegalAccessException {
        Class<?> clazz = object.getClass();
        StringBuilder builder = new StringBuilder();
        builder.append(clazz.getName()).append("\n");
        for (Field field : clazz.getDeclaredFields()) {
            if (!field.isAccessible()) {
                field.setAccessible(true);
            }

            String fieldName = field.getName();
            if (field.isAnnotationPresent(Label.class)) {
                Label label = field.getDeclaredAnnotation(Label.class);
                String name = label.value();
                if (!"".equals(name)) {
                    fieldName = name;
                }
            }
            Object value = field.get(object);
            String valueStr = String.valueOf(value);
            if (value instanceof Date) {
                String format = "yyyy-MM-dd";
                if (field.isAnnotationPresent(Format.class)) {
                    Format formatAnn = field.getDeclaredAnnotation(Format.class);
                    String Annformat = formatAnn.pattern();
                    if (!"".equals(Annformat)) {
                        format = Annformat;
                    }
                }
                SimpleDateFormat formatter = new SimpleDateFormat(format);
                valueStr = formatter.format(value);
            }

            builder.append(fieldName).append("=").append(valueStr).append("\n");

        }
        return builder.toString();
    }
}
